import { create } from "zustand";
import { getRoutes, getCurrentUser } from "@/services/user";
import { setCurrentUser } from "@/utils/authority";

const useUserStore = create(set => ({
	//用户信息
	userInfo: {},

	//菜单数据
	menuData: [],

	//更新用户信息
	updateUserInfo: async () => {
		const { success, data } = await getCurrentUser();
		if (success) {
			set({ userInfo: data });
			setCurrentUser(data);
		}
	},

	//更新菜单信息
	updateMenuData: () => set({ menuData: val }),

	initData: async () => {
		const { success, data } = await getCurrentUser();
		if (success) {
			const res = await getRoutes();
			setCurrentUser(data);
			if(res.success) {
				set({ userInfo: data, menuData: res.data || [] });
			}
		} else {
			window.location.href = '#/user/login'
		}
	}
}));

//获取所有菜单
const getAllRouter = (menu, list) => {
	menu.map(v => {
		if (v.children && v.children.length > 0) {
			return getAllRouter(v.children, list);
		} else {
			list.push(v);
		}
	});
	return list;
};

export default useUserStore;
